package com.liu.netty.demo.client;

import java.util.Arrays;

/**
 * @program: https://www.joinsunsoft.com
 * @description:
 * @author: LiuYong
 * @email: david.liu@ginghan.com
 * @create: 2022/3/23 16:25
 */

public class ByteUtils {

    public static void bytesCopy(byte[] src, int srcPos , byte[] dest, int destPos, int len){
        System.arraycopy(src,srcPos,dest,destPos,len);
        //System.arraycopy(Utilty.int2Bytes(0x9020,2),0,bytes,0,2);
    }

    public static int bytes2Int(byte[] b, int start, int length)
    {
        int sum = 0;
        int end = start + length;
        for (int k = start; k < end; k++)
        {
            int n = b[k] & 0xFF;
            n <<= --length * 8;
            sum += n;
        }
        return sum;
    }

    public static byte[] int2Bytes(int value, int length)
    {
        byte[] b = new byte[length];
        for (int k = 0; k < length; k++) {
            b[(length - k - 1)] = ((byte)(value >> 8 * k & 0xFF));
        }
        return b;
    }

    public static byte[] msg2bytes(String msg, String charset){
        try {
            byte[] buf = msg.getBytes(charset);
            byte[] response = new byte[buf.length + 2];

            ByteUtils.bytesCopy(ByteUtils.int2Bytes(buf.length, 2), 0, response, 0, 2);
            ByteUtils.bytesCopy(buf, 0, response, 2, buf.length);

            return response;
        }catch (Exception e){
            throw new IllegalArgumentException("msg2buf error", e);
        }
    }

    public static String byte2msg(byte[] buf, String charset){
        int i = ByteUtils.bytes2Int(buf, 0,2);

        try {
            String txt =  new String(Arrays.copyOfRange(buf, 2, buf.length), charset);

            return txt;
        }catch (Exception e){
            throw new IllegalArgumentException("msg2buf error", e);
        }
    }
}
